package com.myapi.modeldemo.utils;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @Description:
 * @date 2023/4/4 23:04
 * @Modified By :
 */
public class InsertTask implements Runnable {
    private final List<String> dataList;
    private final DataSource dataSource;
    Connection conn;

    public InsertTask(List<String> dataList) throws SQLException {
        this.dataList = dataList;
        this.dataSource = getDataSource();
        conn = dataSource.getConnection();
    }

    @Override
    public void run() {
        try {
            PreparedStatement ps = conn.prepareStatement("INSERT INTO asentence (sentence,type) VALUES (?,'励志')");
            for (String data : dataList) {
                ps.setObject(1, data);
                ps.addBatch();
            }
            ps.executeBatch();
            System.out.println("插入成功");
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private DataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://101.43.45.238:3306/myapi?useUnicode=true&characterEncoding=utf8&useSSL=false");
        dataSource.setUsername("myapi");
        dataSource.setPassword("123456");
        dataSource.setMaxTotal(20);
        dataSource.setMaxIdle(10);
        dataSource.setMaxWaitMillis(1000); // 设置等待连接的超时时间为1秒
        dataSource.setMinEvictableIdleTimeMillis(1800000); // 设置连接的最大空闲时间为30分钟
        return dataSource;
    }
}
